package com.zoffy.ybuhelper.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.zoffy.ybuhelper.R;
import com.zoffy.ybuhelper.pojo.entity.Category;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class AddCategoryRecyclerAdapter extends RecyclerView.Adapter<AddCategoryRecyclerAdapter.DeleteCategoryViewHolder> {
    private List<Category> dataList;

    public AddCategoryRecyclerAdapter(List<Category> dataList) {
        this.dataList = dataList;
    }

    @NonNull
    @NotNull
    @Override
    public DeleteCategoryViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, null, false);
        return new DeleteCategoryViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull DeleteCategoryViewHolder holder, int position) {
        Category category = dataList.get(position);
        holder.categoryText.setText(category.getName());
        holder.deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = holder.getAdapterPosition();
                dataList.remove(index);
                notifyItemRemoved(index);
            }
        });
    }

    public void addItem(Category category) {
        dataList.add(category);
        notifyItemInserted(dataList.size() - 1);
    }

    public List<Category> getAll(){
        return dataList;
    }
    @Override
    public int getItemCount() {
        return dataList.size();
    }

    protected class DeleteCategoryViewHolder extends RecyclerView.ViewHolder {
        private Button deleteButton;
        private TextView categoryText;

        public DeleteCategoryViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            deleteButton = itemView.findViewById(R.id.delete_category);
            categoryText = itemView.findViewById(R.id.category_name);
        }
    }
}
